package top.chendawei.main.web.controller;

import cn.hutool.json.JSONUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.chendawei.main.facade.UserFacadeImpl;
import top.chendawei.system.beans.entity.SysBlacklist;
import top.chendawei.system.beans.entity.SysUser;
import top.chendawei.system.service.IBlacklistService;
import top.chendawei.system.service.ICommonService;
import top.chendawei.system.service.impl.AuthServiceImpl;
import top.chendawei.util.EncryptTool;
import top.chendawei.util.params.ResultMessage;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/sys/auth")
@Api(tags = "登陆与退出")
public class LoginController {
    @Autowired
    private ICommonService commonService;

    @Autowired
    private AuthServiceImpl authService;

    @Autowired
    private UserFacadeImpl userFacade;

    @Autowired
    private IBlacklistService blacklistService;

    @PostMapping({"/login"})
    public ResultMessage adminLogin(@RequestBody SysUser user) {
        List<SysUser> list = this.commonService.search("username", user.getUsername(), SysUser.class);
        if (list.size() < 1) {
            return ResultMessage.error("用户不存在");
        }
        SysUser dbUser = list.get(0);
        EncryptTool tool = new EncryptTool(user.getUsername());
        String password = tool.decrypt(dbUser.getPassword());
        if (password.equals(user.getPassword())) {
            Map<String, Object> data = Maps.newHashMap();
            if (StringUtils.isNoneBlank(dbUser.getRoleIds())) {
                List<Long> ids = JSONUtil.toList(JSONUtil.parseArray(dbUser.getRoleIds()), Long.class);
                dbUser.setRoleIdList(ids);
                List<String> auths = authService.queryCheckedAuthIdList(ids).stream().map(x -> x + "").collect(Collectors.toList());
                data.put("permissions", auths);
            }
            String token = userFacade.getToken(dbUser);
            data.put("token", token);
            data.put("user", dbUser);
            data.put("expireAt", dbUser.getT() + 30 * 60 * 1000000L);
            data.put("roles", "admin");
            return ResultMessage.success(data);
        }
        return ResultMessage.error("用户名或密码错误");
    }


    @GetMapping({"/permissions"})
    public ResultMessage permissions(HttpServletRequest request) {
        SysUser u = userFacade.getUserFromToken(request);
        if (null == u || null == u.getToken()) {
            return ResultMessage.success("已经退出");
        }
        Map<String, Object> data = Maps.newHashMap();
        if (StringUtils.isNoneBlank(u.getRoleIds())) {
            List<Long> ids = JSONUtil.toList(JSONUtil.parseArray(u.getRoleIds()), Long.class);
            u.setRoleIdList(ids);
            List<String> auths = authService.queryCheckedAuthIdList(ids).stream().map(x -> x + "").collect(Collectors.toList());
            data.put("permissions", auths);
        }
        data.put("user", u);
        data.put("expireAt", u.getT() + 30 * 60 * 1000000L);
        data.put("roles", "admin");
        return ResultMessage.success(data);
    }

    @GetMapping({"/logout"})
    public ResultMessage logout(HttpServletRequest request) {
        SysUser u = userFacade.getUserFromToken(request);
        if (null == u || null == u.getToken()) {
            return ResultMessage.success("已经退出");
        }
        SysBlacklist m = SysBlacklist.builder().token(u.getToken()).time(System.currentTimeMillis()).build();
        blacklistService.save(m);
        return ResultMessage.success();
    }


    @GetMapping({"/routes"})
    public ResultMessage routes(HttpServletRequest request) {
        List<Map<String, Object>> list = Lists.newArrayList();
        Map<String, Object> m = Maps.newHashMap();
        list.add(m);
        m.put("router", "root");
        SysUser curUser = userFacade.getUserFromToken(request);
        List<Map<String, Object>> children = userFacade.queryRouteListByUser(curUser);
        m.put("children", children);
        return ResultMessage.success(list);
    }


    @GetMapping({"/tree"})
    public ResultMessage tree(Long roleId, HttpServletRequest request) {
        Map<String, Object> r = Maps.newHashMap();
        r.put("autoExpandParent", true);
        Set<Long> authIds = new HashSet<>();
        if (null != roleId) {
            authIds = authService.queryCheckedAuthIdList(Arrays.asList(roleId));
        }
        r.put("checkedKeys", authIds);
        Set<Long> expandedKeys = new HashSet<>();

        Map<String, Object> treeData = Maps.newHashMap();
        treeData.put("title", "资源树");
        treeData.put("key", 0L);
        List<Map<String, Object>> children = userFacade.queryAuthTreeByRoleId(expandedKeys);
        treeData.put("children", children);
        List l = new ArrayList<>();
        l.add(treeData);
        r.put("treeData", l);
        r.put("expandedKeys", expandedKeys);
        return ResultMessage.success(r);
    }

    @GetMapping({"/welcome"})
    public ResultMessage welcome(HttpServletRequest request) {
        Map<String, Object> r = Maps.newHashMap();
        r.put("timeFix", "哈哈哈哈");
        r.put("message", "傻逼了吧");
        return ResultMessage.success(r);
    }

    @GetMapping({"/activity"})
    public ResultMessage activity(HttpServletRequest request) {
        List<Map<String, Object>> r = Lists.newArrayList();
        return ResultMessage.success(r);
    }

    @GetMapping({"/team"})
    public ResultMessage team(HttpServletRequest request) {
        List<Map<String, Object>> r = Lists.newArrayList();
        return ResultMessage.success(r);
    }

    @GetMapping({"/project"})
    public ResultMessage project(HttpServletRequest request) {
        List<Map<String, Object>> r = Lists.newArrayList();
        return ResultMessage.success(r);
    }
}
